import { defineStore } from 'pinia'
import { login } from '@/apis/sys/user'
import { store } from '@/store'
import { localSave } from '@/utils/common'

export const useUserStore = defineStore({
    id: 'app-user',
    state: (): UserStore => {
        return {
            token: null,
            uuid: null,
            name: null,
            username: null,
            info: null,
            // user info
            userInfo: null,
            permission: null,
            permissionCodeMap: null,
            tenantId: null,
            productId: null,
            appid: null, // 增加appId
            currentDepartment: undefined
        }
    },
    getters: {
        getToken(state) {
            return state.token
        },
        getUid(state) {
            return state.uuid
        },
        getName(state) {
            return state.name
        },
        getUserInfo(state) {
            return state.userInfo
        },
        getPermission(state) {
            return state.permission
        },
        getPermissionMap(state) {
            return state.permissionCodeMap
        },
        getCurrentDepartment(state) {
            return state.currentDepartment
        }
    },
    actions: {
        login(loginForm: LoginForm): Promise<LoginResponse> {
            return login(loginForm).then(resp => {
                this.token = resp.token
                this.uuid = resp.uuid
                localSave('al__Access-Token', resp.token)
                localSave('al__UID', resp.uuid)
                return resp
            })
        },
        logout() {
            this.token = null
            this.uuid = null
            this.name = null
        },
        setUserInfo(userInfo: UserInfo) {
            this.userInfo = userInfo
            if (!userInfo) {
                // TODO: clean info
                return
            }
            const { id, username, email, gender, mobile, name, tenantId } = userInfo
            // @ts-ignore
            this.info = { id, username, email, gender, mobile, name, tenantId }
            this.username = username
            this.name = name ? name : null
            localSave('al__USER_INFO', userInfo)
        },
        buildPermissionInfo(permission: UserPermissionInfo[]) {
            this.permission = permission
            if (!permission) {
                return
            }
            // 转换成字符串并用正则提取处code，避免递归
            const permissionCodeArr = JSON.stringify(permission).match(/"code":"(.+?)"/g)
            const permissionCodePure =
                permissionCodeArr?.map(item => {
                    const codeStr = item.match(/"code":"(.+?)"/)
                    return codeStr && codeStr.length > 0 ? codeStr[1] : ''
                }) || []
            // 增加权限码映射表，避免递归查找
            this.permissionCodeMap = Array.from(new Set(permissionCodePure))
        },
        setCurrentDepartment(departmentId?: number | number[]) {
            this.currentDepartment = departmentId
            localSave('al__DepartmentId', departmentId)
        }
    },
    persist: {
        enabled: true,
        strategies: [{ storage: localStorage, paths: ['token', 'uuid', 'productId', 'tenantId', 'appid'] }]
    }
})

// Need to be used outside the setup
export function useUserStoreWithOut() {
    return useUserStore(store)
}
